import {
  createStore
} from "vuex";
import host from '@/utils/ipConfig.js'
import {
  initializeAppApi
} from '../api/login.js'
import {
  getPraiseApi
} from '@/api/praise.js'

export default createStore({
  state: {
    businessInfo: {},
    userCollectInfo: {},
    collectNum: 0
  },
  getters: {
    getBusinessInfo(state) {
      return state.businessInfo
    },
    getUserCollectInfo(state) {
      return state.userCollectInfo
    },
    getCollectNum(state) {
      return state.collectNum
    }
  },
  mutations: {
    SET_BUSINESS_INFO(state, businessInfo) {
      state.businessInfo = businessInfo;
    },
    SET_USER_COLLECT_INFO(state, info) {
      state.userCollectInfo = info
    },
    SET_COLLECT_NUM(state, collectNum) {
      state.collectNum = collectNum
    }
  },
  actions: {
    // 获取商家信息，用于渲染小程序
    async setBusinessInfo(context) {
      try {
        const openId = uni.getStorageSync('openid')
        const {
          code,
          data
        } = await initializeAppApi({
          openid: openId ?? '',
          businessId: host.appId
        })
        if (code === '000000') {
          uni.setStorageSync('businessInfo', JSON.stringify(data))
          context.commit('SET_BUSINESS_INFO', data)
        }
      } catch (e) {
        return Promise.reject(e)
      }
    },
    // 获取用户喜欢信息
    async setUserCollectInfo({
      commit
    }) {
      try {
        const openid = uni.getStorageSync('openid')
        if (openid) {
          const {
            code,
            data
          } = await getPraiseApi(openid)
          if (code === '000000') {
            const userCollectInfo = data ?? {
              prodDetailBos: [],
              prodPiclists: [],
              userReserveDTOs: []
            }
            let collectNum = Object.values(userCollectInfo)?.reduce((sum, curr) => sum + (curr?.length ?? 0), 0)
            commit('SET_USER_COLLECT_INFO', userCollectInfo)
            commit('SET_COLLECT_NUM',collectNum)
          }
        }
      } catch (e) {
        console.log(e)
      }
    }
  },
});
